import { defineStore } from "pinia";
import { setToken, removeToken } from '@/utils/token'

const userInfoStore = defineStore('userInfo', {
  state : () => {
  return {
    token: '', // 登录token
    info: {},  // 用户信息
  }
  },
  getters: {
    getToken() {
      return this.token
    }
  },

  actions:{
    tokenChange( token) {
      this.token = token
    },
    infoChange( info) {
      this.info = info
    },
    login( params) {
      return new Promise((resolve, reject) => {
        loginApi(params)
        .then(res => {
          const token = res.data.token
          this.tokenChange (token)
          setToken(token)
          // this.getInfo({ token: res.data.token })
          
        }).catch(err => {
          reject(err)
        })
      })
    },
    // get user info after user logined
    getInfo( params) {
      return new Promise((resolve, reject) => {
        getInfoApi(params)
        .then(res => {
          this.infoChange(res.data.info)
          resolve(res.data.info)
        })
      })
    },
  
    // login out the system after user click the loginOut button
    loginOut() {
      loginOutApi()
      .then(res => {
  
      })
      .catch(error => {
  
      })
      .finally(() => {
        removeToken()
        location.reload()
      })
    }
  }
})

export default userInfoStore